package com.ee.chat.api.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.IPUtil;
import com.ndhutu.ee.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求参数打印
 * @Author Shane
 * @Date 2019/10/6 21:19
 */
@Component
public class LogInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(LogInterceptor.class);
    private ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> params = new HashMap<>();

        String ip = IPUtil.getClientIP(request);
        String url = request.getRequestURL().toString();
        String mothod = request.getMethod();

        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String parameterName = parameterNames.nextElement();
            params.put(parameterName, request.getParameter(parameterName));
        }

        threadLocal.set(System.currentTimeMillis());

        log.info("------------start------------");
        log.info("请求地址：" + url);
        log.info("请求类型：" + mothod);
        log.info("请求ip：" + ip);
        Object token = params.get("token");
        if(token != null && !StringUtil.isEmpty(token)){
            String key = ConstantsUtil.USER_TOKEN + token;
            Object userId = redisTemplate.boundHashOps(key).get("userId");
            log.info("用户id：" + userId);
        }
        log.info("设备信息：" + params.get("extra"));
        params.remove("extra");
        log.info("请求参数：" + JSONObject.toJSONString(params));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("请求耗时：" + (System.currentTimeMillis() - threadLocal.get())/ 1000.0 +"秒");
        log.info("------------end------------");
    }
}
